package com.liaoye.hellocustomview.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Shader;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.liaoye.hellocustomview.R;

/**
 * 图片着色器
 */
public class BitmapShaderView extends View {

    private Paint mPaint;
    private Bitmap mBitmap;

    public BitmapShaderView(Context context) {
        super(context);
        init();
    }

    public BitmapShaderView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public BitmapShaderView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        setLayerType(LAYER_TYPE_SOFTWARE, null);
        //设置画笔的基本属性
        mPaint = new Paint();

        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.dog);

        Log.i("BitmapShaderView", "init: " + mBitmap.getByteCount() + " width = " + mBitmap.getWidth()
                + " width = " + mBitmap.getHeight() + " height = " + mBitmap.getHeight() + " " + getResources().getDisplayMetrics().toString());
        mPaint.setShader(new BitmapShader(mBitmap, Shader.TileMode.REPEAT, Shader.TileMode.REPEAT));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

//        canvas.drawRect(0, 0, getWidth(), getHeight(), mPaint);

        float left = getWidth() / 3;
        float top = getHeight() / 3;
        float right = getWidth() * 2 / 3;
        float bottom = getWidth() * 2 / 3;
        canvas.drawRect(left, top, right, bottom, mPaint);

    }

    public void setShader(Shader.TileMode tileMode){
        mPaint.setShader(new BitmapShader(mBitmap, tileMode, tileMode));
        invalidate();
    }
}
